package com.liusha.quicksand.interceptor;

import com.liusha.quicksand.po.User;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: 一世长安一世欢
 * @Date: 2020/10/25
 * @Time: 11:22
 * @Description: No Description
 */
public class CheckUserInterceptor implements HandlerInterceptor {

    String[] res = {".js", ".css", ".html", ".htm", "/login", "/error", ".jpg", ".png", ".jpeg", ".gif"};

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String path = request.getRequestURI();
        for (String s : res) {
            if (path.endsWith(s)){
                return HandlerInterceptor.super.preHandle(request,response,handler);
            }
        }

        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        if (user == null || user.getUserId() == null || user.getUserId() <= 0) {
            response.sendRedirect("/login");
            return false;
        }
        return HandlerInterceptor.super.preHandle(request, response, handler);
    }
}
